<template>
    <div class="article-list">
        <!-- 文章列表组件 -->
        <van-pull-refresh v-model="refreshing" success-text="刷新成功" @refresh="onRefresh">
            <van-list
                v-model="loading"
                :finished="finished"
                finished-text="没有更多了"
                :error.sync="error"
                error-text="请求失败，点击重新加载"
                @load="onLoad"
            >
                <!-- <van-cell
                    v-for="(item, index) in list"
                    :key="index"
                    :title="item.title"
                /> -->
                <ArticleItem 
                    v-for="(item, index) in list"
                    :key="index"
                    :article="item" 
                />
            </van-list>
        </van-pull-refresh>
    </div>
</template>

<script>
import { getArticles } from "@/api/article";
import ArticleItem from "@/components/article-item";
export default {
    name: "ArticleList",
    components:{ArticleItem},
    props: {
        channel: {
            type: Object,
            required: true,
        },
    },
    data() {
        return {
            list: [],
            loading: false,
            finished: false,
            timestamp: null,
            error: false,
            refreshing: false,
        };
    },
    methods: {
        async onLoad() {
            // 异步更新数据
            try {
                const { data } = await getArticles({
                    channel_id: this.channel.id,
                    timestamp: this.timestamp || Date.now(),
                    with_top: 1,
                });
                this.list.push(...data.data.results);
                this.loading = false;
                if (data.data.results.length) {
                    this.timestamp = data.data.pre_timestamp;
                } else {
                    this.finished = true;
                }
            } catch (err) {
                this.error = true;
                this.loading = false;
            }
        },
        async onRefresh() {
            // 清空列表数据
            try {
                const { data } = await getArticles({
                    channel_id: this.channel.id,
                    timestamp: Date.now(),
                    with_top: 1,
                });
                this.list.unshift(...data.data.results);
                this.finished = false;
            } catch (error) {
                
            }
        },
    },
};
</script>

<style lang="less" scoped>
.article-list{
    height: 79vh;
    overflow-y: auto;
}
</style>